<?php
namespace app\admin\controller;
use x\my\Umeng;
class User extends Base
{
    //列表
    public function lists(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!='') $map[] = ['and','a.username|a.name|a.phone','like',"%{$d['keyword']}%"];
            if($d['level']!='') $map[] = ['and','a.level','=',$d['level']];
            if($d['status']!='') $map[] = ['and','a.status','=',$d['status']];
            if($d['min_time']!='') $map[] = ['and','a.create_time','>=',strtotime($d['min_time'])];
            if($d['max_time']!='') $map[] = ['and','a.create_time','<=',strtotime($d['max_time'])];
            $w  = where($map);
            $rs = $this->db->query("select a.*,b.username s_username from user a left join user b on a.s_id = b.id $w[0] order by id desc".limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                $rule = [
                    'status' => function($v){return c("type.status.{$v}");},
                    'is_rz' => function($v){return c("type.is_rz.{$v}");},
                    'level' => function($v){return c("type.user_level.{$v}");},
                    'sex' => function($v){return c("type.sex.{$v}");},
                    'create_time' => 'com_time_format',
                ];
                $data = com_format($rs[0],$rule);
                suc($data,$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch();
    }

    //加密方式
    public function com_password($password,$salt=''){
        return md5(md5($password).$salt);
    }

    //编辑
    public function edit(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'phone'  =>'require|mobile|unique:user,phone,'.$d['id'].',id',
                'level' => 'require',
            ];
            $msg = [
                'phone.require' => '手机号码不能为空',
                'phone.mobile' => '手机号码格式错误',
                'phone.unique' => '手机号已存在',
                'level.require' => '级别不能为空',
            ];
            check($rule,$msg,$d);
            if ( !empty($d['password']) ) {
                $d['password'] = $this->com_password($d['password']);
            }else{
                unset($d['password']);
            }
            if ( !empty($d['s_password']) ) {
                $d['s_password'] = $this->com_password($d['s_password']);
            }else{
                unset($d['s_password']);
            }

            //验证推荐人
            $old_userinfo = $this->db->find('user',$d['id']);
            $new_userinfo = $d;

            #老的推荐人
            $old_suser    = $this->db->find('user',$old_userinfo['s_id']);

            #新的推荐人
            $new_suser    = $this->db->query("select * from user where phone=?",[$d['sphone']],1);
            $new_suser    = $new_suser?$new_suser:[];

            $type = $this->_check($old_userinfo, $new_userinfo, $old_suser, $new_suser);

            $this->db->begin();
            $mysql   = [];
            //更新了推荐人
            if($type==1){
                #已经存在上级
                if ($old_userinfo['s_id']) {
                    #找出下级id
                    $self_tree = $old_userinfo['s_tree'].$old_userinfo['id'].',%';
                    $b_rs = $this->db->query("select id from user where s_level>? and s_tree like ?",[$old_userinfo['s_level'],$self_tree]);
                    $b_ids = array_column($b_rs, 'id');

                    #修改推荐人
                    #新推荐人的tree,level
                    $s_tree = $new_suser['s_tree'];
                    #修改自己的推荐关系
                    $s_data = [
                        'id'     => $old_userinfo['id'],
                        's_id'   => $new_suser['id'],
                        's_tree' => $s_tree.$new_suser['id'].',',
                        's_level' => $new_suser['s_level']+1,
                    ];
                    $mysql[] = $this->db->update('user',$s_data);

                    //改变的层数
                    $add = count(explode(",", $s_tree)) - count(explode(",", $old_suser['s_tree']));
            
                    #遍历修改自己推荐下级会员的tree
                    if($b_ids){
                        $b_ids = implode(",", $b_ids);
                        $old_tree = $old_userinfo['s_tree'].$old_userinfo['id'].',';
                        $new_tree = $s_tree.$new_suser['id'].','.$old_userinfo['id'].',';
                        if ( $add >= 0 ) {
                            $mysql[] = $this->db->query("update user set s_tree=REPLACE(s_tree,'{$old_tree}','{$new_tree}') ,s_level=s_level+$add  where id in ({$b_ids})");
                        }
                        if ( $add < 0 ) {
                            $add = abs($add);
                            $mysql[] = $this->db->query("update user set s_tree=REPLACE(s_tree,'{$old_tree}','{$new_tree}') ,s_level=s_level-$add  where id in ({$b_ids})");
                        }
                    }
                    $mysql[] = $this->db->query("update user set s_nums=s_nums+? where id=?",[1,$new_suser['id']]);
                    $mysql[] = $this->db->query("update user set s_nums=s_nums-? where id=?",[1,$old_userinfo['s_id']]);

                    //记录log
                    m('Log','xcom')->record($this->userinfo['id'],'修改用户推荐关系:['.$old_userinfo['name'].']'.$old_userinfo['id'].'的推荐人['.$old_userinfo['s_id'].']为['.$new_suser['id'].']','admin_user');
                    
                }else{
                    #修改自己的推荐关系
                    $s_data = [
                        'id'     => $old_userinfo['id'],
                        's_id'   => $new_suser['id'],
                        's_tree' => $new_suser['s_tree'].$new_suser['id'].',',
                        's_level' => $new_suser['s_level']+1,
                    ];
                    $mysql[] = $this->db->update('user',$s_data);

                    $mysql[] = $this->db->query("update user set s_nums=s_nums+? where id=?",[1,$new_suser['id']]);
                    //记录log
                    m('Log','xcom')->record($this->userinfo['id'],'修改用户推荐关系:['.$old_userinfo['name'].']'.$old_userinfo['id'].'的推荐人['.$old_userinfo['s_id'].']为['.$new_suser['id'].']','admin_user');
                }
            //没有更新推荐人
            }
            
            unset($d['sphone']);
            $this->db->update("user",$d);
            
            if ($old_userinfo['level']!=$d['level']) {
                m('Log','xcom')->record($this->userinfo['id'],'修改用户级别id['.$d['id'].']:'.c('type.user_level')[$old_userinfo['level']].'=>'.c('type.user_level')[$d['level']],'admin_user');
            }
            m('Attachment','xcom')->imgSure('user',$d['id'],$d);
            m('Log','xcom')->record($this->userinfo['id'],'编辑用户资料:'.json_encode($d,JSON_UNESCAPED_UNICODE),'admin_user');
            $rs = $this->db->end($mysql);
            if ($rs) {
                cookie('js_msg','修改成功');
                cookie('js_function','preload');
                return suc();
            }else{
                err('修改失败');
            }
            
        }
        $id = $this->get["id"];
        $sql = "select a.*,b.phone as sphone from user a left join user b on a.s_id=b.id where a.id=?";
        $info = $this->db->query($sql,[$id],1);
        $this->fetch(["info" => $info]);
    }

    /**
     * 验证tuijianren
     * @param  [type] $old_userinfo [老信息]
     * @param  [type] $new_userinfo [新信息]
     * @param  [type] $old_suser    [老推荐人信息]
     * @param  [type] $new_suser    [新推荐人信息]
     */
    private function _check($old_userinfo, $new_userinfo, $old_suser, $new_suser){
        
        if($old_userinfo['level']>0 && $new_userinfo['level']<1){
            err('云店用户不能更改为普通用户');
        }

        if($new_userinfo['level']>0){
            if(!isset($new_suser['id'])){
                err('云店用户，必须要有推荐人');
            }
        }else{
            if(isset($new_suser['id'])){
                err('普通用户，不能有推荐人');
            }
        }

        if (isset($new_suser['id'])) {
            #没改推荐人
            if($new_suser['id'] == $old_userinfo['s_id']){
                return false;
            #改了推荐
            }else{
                if ( $new_userinfo['id'] == 10000 ) err('系统第一人不能修改');
                //推荐人必须是云店， 而且不是是自己和自己的下级会员
                if ($new_suser['level']<1) {
                    err('推荐人不能为普通用户');
                }

                #推荐人不能是自己 #推荐人不能是自己的下级
                $self_tree = $old_userinfo['s_tree'].$old_userinfo['id'].',%';
                $b_rs = $this->db->query("select id from user where  s_tree like ?",[$self_tree]);
                $b_ids = array_column($b_rs, 'id');
                #推荐编号不能是自己 #推荐编号不能是下级
                if ( $new_suser['id'] == $old_userinfo['id'] || in_array($new_suser['id'],$b_ids) ){
                    err('推荐用户不能是自己或下级');
                } 
                return true;
            }
        }else{
            return false;
        }
        

    }

    //变动资金
    public function editMoney(){
        if (is_post()) {
            $d = $this->post;
            $rule = [
                'id'         =>  'require',
                'money_type' => 'require',
                'money'      =>  'require|float',
                'note'       =>  'require',
            ];
            $msg = [
                'money_type.require' =>'币种不能为空',
                'money.require' =>'金额不能为空',
                'money.float'   =>'金额格式不对',
                'note.require'  =>'请填写备注信息',
            ];
            check($rule,$msg,$d);
            $rs = s('OrderUmoney','c')->doit($d['id'], $this->userinfo['id'], $d['money_type'], $d['money'], $d['note']);
            cookie('js_function','preload');
            if($rs){
                cookie('js_msg','变动资金成功');
                suc();
            }else{
                err(s('OrderUmoney','c')->getError());
            }
        }
        $id=$this->get('id');
        //模板赋值
        $info = $this->db->find('user',$id);
        $this->fetch(['info'=>$info]);
    }

    //t推送
    //推送
    public function tuisong(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'id'  =>  'require',
                'msg' => 'require',
            ];
            $msg = [];
            check($rule,$msg,$d);
            $info = $this->db->find('user',$d['id']);
            if($info && !$info['tuisong_token']) err('用户未更新推送token');
            $rs = Umeng::send($info['tuisong_token'], $d['msg']);
            if($rs){
                $data = [
                    "table" => "user",
                    "table_id" => $d['id'],
                    "title" => $d['msg'],
                    "content" => $d['msg'],
                    "create_time" => time(),
                ];
                $this->db->insert("com_message",$data);
                return suc();
            }else{
                return err('推送失败');
            }
        }
        $id = $this->get("id");
        $info = $this->db->find('user',$id);
        $this->fetch(['info'=>$info]);
    }

    //详情
    public function details(){
        $id = $this->get("id");
        $map = [];
        $map[] = ['and','s_id','=',$id];
        $w  = where($map);
        #推荐列表
        $list = $this->db->query("select * from user $w[0] order by id desc", $w[1]);
        #用户信息
        $info = $this->db->query("select a.*,b.username as relation_username from user a left join user b on a.relation_id=b.id where a.id = ?",[$id],1);

        $this->fetch(['info'=>$info,'list'=>$list]);
    }
}
